<?php

/**
 * Contains Application class
 *
 * LICENSE: MIT
 *
 * @author Peter Pippinger
 * @category PP
 * @package PP_Application
 * @copyright Copyright (c) 2013 Peter Pippinger
 * @license http://opensource.org/licenses/MIT
 * @version 1.1.0
 * @since Class exists since release 1.0.0
 */

/**
 * Application class
 *
 * Provides handling for Application access
 *
 * @author Peter Pippinger
 * @category PP
 * @package PP_Application
 * @copyright Copyright (c) 2013 Peter Pippinger
 * @license http://opensource.org/licenses/MIT
 * @version 1.1.0
 * @since Class exists since release 1.0.0
 */
class Application
{

	/**
	 * Debug mode.
	 *
	 * @var boolean
	 */
	private static $_debug = false;

	/**
	 * Unique browser id.
	 *
	 * @var string
	 */
	public static $_browserId = '';

	/**
	 * Database handle.
	 *
	 * @var database handle
	 */
	public static $mysqli = '';

	/**
	 * Application settings.
	 *
	 * @var array
	 */
	private static $_applicationSettings = array();

	/**
	 * Initializes the application class.
	 *
	 * @param array $dbSettings        	
	 */
	public static function init(array $applicationSettings)
	{
		self::$_applicationSettings = $applicationSettings;
		
		// Try to get browser id from cookie.
		if (isset($_COOKIE['browser_id']) && $_COOKIE['browser_id'] != '') {
			Application::$_browserId = $_COOKIE['browser_id'];
		} else {
			Application::$_browserId = Application::getNewBrowserId();
		}
		
		// Refresh the cookie.
		setcookie('browser_id', Application::$_browserId, time() + (86400 * 365));
		
		// Connect to database.
		Application::$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
		Application::$mysqli->query('CREATE DATABASE IF NOT EXISTS `' . DB_DATABASE . '`');
		Application::$mysqli->select_db(DB_DATABASE);
		Application::$mysqli->query('CREATE TABLE IF NOT EXISTS `playlist` (
			`server_id` varchar(8) NOT NULL,
			`client_id` varchar(8) NOT NULL,
			`sortsequence` int(11) NOT NULL,
			`video_id` varchar(11) NOT NULL,
			`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			KEY `server_id` (`server_id`,`client_id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
	}

	/**
	 * Gets a new unique browser id.
	 *
	 * @return string
	 */
	private static function getNewBrowserId()
	{
		return substr(md5(microtime() . SALT), 0, 8);
	}

	/**
	 * Gets the application settings.
	 *
	 * @return array
	 */
	public static function getApplicationSettings()
	{
		return self::$_applicationSettings;
	}
}
